﻿using System;
using System.Text;
using System.Data;
using BDElectron.Remote;
using BDElectron.Platform;
using BDElectron.Utils;


namespace BDElectron.Server
{
    public class ServerObject : MarshalByRefObject, IServerObject, IDisposable
    {
        public DataTable mTableNames;
        public DataTable mTableFieldNames;
        string mUser = string.Empty;
        int mUserID = -1;

        DataBridge mDataBridge = null;
        private string mLastError = string.Empty;

        string IServerObject.User
        {
            get { return mUser; }
        }

        int IServerObject.UserID
        {
            get { return mUserID; }
        }

        private ServerObject()
        {
            mDataBridge = new DataBridge();

            string commandTableList = @"SELECT " + UFT.Table_TableList.COLUMN_TableID
                + ", " + UFT.Table_TableList.COLUMN_TableNameDB
                + " FROM " + UFT.Table_TableList.TABLE_NAME;

            string commandFieldList = @"SELECT " + UFT.Table_FieldsList.COLUMN_FieldID
                + ", " + UFT.Table_FieldsList.COLUMN_FieldNameDB
                + " FROM " + UFT.Table_FieldsList.TABLE_NAME;

            if (mDataBridge.Connect() == true)
            {
                mTableNames = mDataBridge.ExecuteQuery(commandTableList);
                mLastError = mDataBridge.LastError;

                mTableFieldNames = mDataBridge.ExecuteQuery(commandFieldList);
                mLastError = mDataBridge.LastError;
                mDataBridge.Disconnect();
            }
            else
            {
                throw new Exception("HRPM server application failed to connect to DB. " + mLastError);
            }

            if (!mLastError.Equals(string.Empty))
            {
                throw new Exception(mLastError);
            }

           // AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        public ServerObject(string login, string password)
        {
            mDataBridge = new DataBridge();           

            if (mLastError.Equals(string.Empty))
            {
                if (!Login(login, password))
                {
                    if (!mLastError.Equals(string.Empty))
                    {
                        throw new Exception(mLastError);
                    }
                }
            }
            else
            {
                throw new Exception(mLastError);
            }
        }
        
        public bool Login(string user, string password)
        {            
            mDataBridge = new DataBridge();

            bool result = false;

            try
            {
                if (mDataBridge.Connect() == true)
                {
                    string commandText = "SELECT UserID, Login, FirstName, LastName FROM Users WHERE Login = '" + user + "' AND Password='" + password + "'";
                    DataTable loginResult = mDataBridge.ExecuteQuery(commandText);
                    if (loginResult != null && loginResult.Rows.Count == 1)
                    {
                        mUser = loginResult.Rows[0]["Login"].ToString();
                        string strmUserID = loginResult.Rows[0]["UserID"].ToString();
                        int.TryParse(strmUserID, out mUserID);                        

                        result = true;
                    }
                }
            }
            finally
            {
                mDataBridge.Disconnect();
            }

            Console.Write("Authentication request from user \"");
            ConsoleColor oldColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(user);
            Console.ForegroundColor = oldColor;
            Console.WriteLine("\" - " + (result ? "Success" : "Failure").ToString());
            return result;
        }


        #region IDisposable members
        void IDisposable.Dispose()
        {
            mDataBridge.Disconnect();
            LogDebug("ServerObject.Dispose()");
        }
        #endregion IDisposable members

        void IServerObject.LogDebug(string message)
        {
            LogDebug(message);
        }

        private void LogDebug(string message)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[USER: ");
            sb.Append(mUserID);
            sb.Append(":");
            sb.Append(mUser);
            sb.Append("]");
            sb.Append(" - ");
            sb.Append(message);

            Logger.LogDebug(sb.ToString());
        }


        DataTable IServerObject.GetUsersList()
        {
            DataTable usersList = new DataTable();

            try
            {
                if (mDataBridge.Connect() == true)
                {

                    string commandText = @"SELECT * FROM USERS ";

                    usersList = mDataBridge.ExecuteQuery(commandText);
                    mLastError = mDataBridge.LastError;
                }
            }
            finally
            {
                mDataBridge.Disconnect();
            }

            return usersList;
        }


    }
}
